<route lang="yaml">
meta:
  title: 视频生成
</route>

<script setup lang="ts">
import {ElNotification, type FormInstance, type FormRules} from 'element-plus';
import { FolderOpened } from '@element-plus/icons-vue';
import {VideoProcessor} from "@/utils/ffmpeg.ts";

interface FormState {
  inputPath: string;
  outputPath: string;
  videoCount: number;
  startPercentage: number;
  endPercentage: number;
  videoSpeed: number;
  inputFormat: string;
}

// 实例化 VideoProcessor 类
const videoProcessor = new VideoProcessor();

// Electron环境下的文件夹选择实现
const selectInputFolder = async () => {
  try {
    // 调用 Electron 主进程的文件夹选择对话框
    const result = await window.electronAPI?.openFolderDialog();
    if (result) {
      formValue.inputPath = result;
    }
  } catch (error) {
    console.error('选择输入文件夹失败:', error);
  }
};

const selectOutputFolder = async () => {
  try {
    // 调用 Electron 主进程的文件夹选择对话框
    const result = await window.electronAPI?.openFolderDialog();
    if (result) {
      formValue.outputPath = result;
    }
  } catch (error) {
    console.error('选择输出文件夹失败:', error);
  }
};

const formRef = ref<FormInstance>();

const processing = ref(false);

const formValue = reactive<FormState>({
  inputPath: '',
  outputPath: '',
  videoCount: 5,
  startPercentage: 0,
  endPercentage: 100,
  videoSpeed: 1.0,
  inputFormat: 'mp4'
});

const rules = reactive<FormRules>({
  inputPath: [
    { required: true, message: '请输入输入文件夹路径', trigger: 'blur' }
  ],
  outputPath: [
    { required: true, message: '请输入输出文件夹路径', trigger: 'blur' }
  ],
  videoCount: [
    { required: true, message: '请输入选取视频个数', trigger: 'blur' }
  ],
  startPercentage: [
    { required: true, message: '请输入开始区间', trigger: 'blur' }
  ],
  endPercentage: [
    { required: true, message: '请输入结束区间', trigger: 'blur' }
  ],
  videoSpeed: [
    { required: true, message: '请输入视频加速值', trigger: 'blur' }
  ],
  inputFormat: [
    { required: true, message: '请选择输入格式', trigger: 'change' }
  ]
});

const formatOptions = [
  { label: 'mp4', value: 'mp4' },
  { label: 'avi', value: 'avi' },
  { label: 'mov', value: 'mov' },
  { label: 'mkv', value: 'mkv' },
  { label: 'flv', value: 'flv' }
];

const handleProcess = async (e: Event) => {
  e.preventDefault();
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      processing.value = true;
      // 这里应该调用实际的视频处理函数
      processVideos(formValue)
        .finally(() => {
          processing.value = false;
        });
    } else {
      console.log('表单验证失败', fields);
    }
  });
};

// 处理视频的主要函数
const processVideos = async (config: FormState): Promise<void> => {
  return new Promise((resolve) => {
    console.log('开始处理视频，配置信息:', config);
    const options = {
      startPercent: config.startPercentage ?? '',
      endPercent: config.endPercentage ?? '',
      speed: config.videoSpeed ?? '',
      format: config.inputFormat ?? ''
    }

    videoProcessor.randomSelectAndMerge(config.inputPath, config.videoCount, config.outputPath, options).then(result => {
      console.log(result)
      ElNotification({
        title: '提示',
        message: '成功',
        type: 'success',
      })
    }).catch( error => {
      ElNotification({
        title: '提示',
        message: error,
        type: 'error',
      })
    })
    resolve();
  });
};
</script>

<template>
  <div>
    <FaPageMain>
      <el-card class="video-config-card">
        <template #header>
          <div class="card-header">
            <span>视频处理配置</span>
          </div>
        </template>

        <el-form
          :model="formValue"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="输入文件夹" prop="inputPath">
            <el-input v-model="formValue.inputPath" placeholder="请输入视频文件所在文件夹路径">
              <template #append>
                <el-button @click="selectInputFolder">
                  <el-icon><folder-opened /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="输出文件夹" prop="outputPath">
            <el-input v-model="formValue.outputPath" placeholder="请输入处理后视频保存路径">
              <template #append>
                <el-button @click="selectOutputFolder">
                  <el-icon><folder-opened /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="选取视频个数" prop="videoCount">
            <el-input-number v-model="formValue.videoCount" :min="1" controls-position="right" style="width: 100%" />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始区间(%)" prop="startPercentage">
                <el-input-number v-model="formValue.startPercentage" :min="0" :max="100" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束区间(%)" prop="endPercentage">
                <el-input-number v-model="formValue.endPercentage" :min="0" :max="100" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="视频加速" prop="videoSpeed">
                <el-input-number v-model="formValue.videoSpeed" :min="0.1" :step="0.1" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="输入格式" prop="inputFormat">
                <el-select v-model="formValue.inputFormat" placeholder="请选择输入格式" style="width: 100%">
                  <el-option
                    v-for="item in formatOptions"
                    :key="item.value"
                    :label="item.label.toUpperCase()"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="handleProcess" :loading="processing">开始处理</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </FaPageMain>
  </div>
</template>
